<template>
	<view class="fix-top-window">
		<view class="uni-header">
			<view class="uni-group hide-on-phone">
				<view class="uni-title">{{$t('user.text.userManager')}}</view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">

				<input class="uni-search" type="text" v-model="searchParams.mobile" placeholder="手机号" />

				<input class="uni-search" type="text" v-model="searchParams.username" placeholder="用户名" />


				<input class="uni-search" type="text" v-model="searchParams.student_name" placeholder="学生名称" />

				<button class="uni-button" type="default" size="mini"
					@click="search">{{$t('common.button.search')}}</button>


				<button class="uni-button" type="primary" size="mini"
					@click="toAdd">{{$t('common.button.add')}}</button>
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">{{$t('common.button.batchDelete')}}</button>
				<!-- 	<button class="uni-button" type="primary" size="mini" :disabled="!selectedIndexs.length"
					@click="openTagsPopup">标签管理</button> -->
				<!-- #ifdef H5 -->
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
				<!-- #endif -->
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collection"
				:where="getInfoWhere" page-data="replace" :orderby="orderby" :getcount="true"
				:page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || $t('common.empty')" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'username')"
							sortable @sort-change="sortChange($event, 'username')">用户名</uni-th>
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'student_name')" sortable
							@sort-change="sortChange($event, 'student_name')">学生名称</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'mobile')"
							sortable @sort-change="sortChange($event, 'mobile')">手机号码</uni-th>
						<uni-th align="center">
							使用次数
						</uni-th>
						<uni-th align="center">
							登录次数
						</uni-th>
						<uni-th align="center" filter-type="select" :filter-data="options.filterData.status_localdata"
							@filter-change="filterChange($event, 'status')">用户状态</uni-th>
						<uni-th align="center">
							考试时间
						</uni-th>
						<uni-th>
							考试科目
						</uni-th>
						<uni-th>
							考试车型
						</uni-th>
						<uni-th>
							考试证件
						</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'email')"
							sortable @sort-change="sortChange($event, 'email')">邮箱</uni-th>
						<uni-th align="center">角色</uni-th>
						<uni-th align="center">所属机构</uni-th>
						<uni-th align="center" filter-type="select" :filter-data="tagsData"
							@filter-change="filterChange($event, 'tags')">用户标签</uni-th>
						<uni-th align="center">可登录应用</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'register_date')" sortable
							@sort-change="sortChange($event, 'register_date')">注册时间</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.username}}</uni-td>
						<uni-td align="center">{{item.student_name}}</uni-td>
						<uni-td align="center">{{item.mobile}}</uni-td>
						<uni-td align="center">{{item.use_times}}</uni-td>
							<uni-td align="center">{{item.login_times}}</uni-td>
						<uni-td align="center">{{options.text[item.fee_status]}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :date="item.test_times"></uni-dateformat>
						</uni-td>
						<uni-td align="center">{{subjectList[item.type_subject_id]}}</uni-td>
						<uni-td align="center">{{driveList[item.type_drive_id]}}</uni-td>
						<uni-td align="center">{{certList[item.type_cert_id]}}</uni-td>

						<uni-td align="center">
							<uni-link :href="'mailto:'+item.email" :text="item.email"></uni-link>
						</uni-td>
						<uni-td align="center">{{item.role}}</uni-td>
						<uni-th align="center">{{getNameValue(item.mechanism_id)}}</uni-th>
						<uni-td align="center">
							<template v-if="item.tags" v-for="tag in item.tags">
								<uni-tag type="primary" inverted size="small" :text="tag" style="margin: 0 5px;">
								</uni-tag>
							</template>
						</uni-td>
						<uni-td align="center">
							<uni-link v-if="item.dcloud_appid === undefined" :href="noAppidWhatShouldIDoLink">
								未绑定可登录应用<view class="uni-icons-help"></view>
							</uni-link>
							{{item.dcloud_appid}}
						</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.register_date"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="toEdit(item)" class="uni-button" size="mini"
									type="primary">{{$t('common.button.edit')}}</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">{{$t('common.button.delete')}}</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<!-- #ifndef MP -->
					<picker class="select-picker" mode="selector" :value="pageSizeIndex" :range="pageSizeOption"
						@change="changeSize">
						<button type="default" size="mini" :plain="true">
							<text>{{pageSizeOption[pageSizeIndex]}} {{$t('common.piecePerPage')}}</text>
							<uni-icons class="select-picker-icon" type="arrowdown" size="12" color="#999"></uni-icons>
						</button>
					</picker>
					<!-- #endif -->
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
		<uni-popup ref="tagsPopup" type="center">
			<view class="tags-manager--x">
				<view class="tags-manager--header mb">管理标签</view>
				<uni-data-checkbox ref="checkbox" v-model="managerTags" class="mb ml" :multiple="true"
					collection="uni-id-tag" field="tagid as value, name as text"></uni-data-checkbox>
				<view class="uni-group">
					<button @click="managerMultiTag('add')" class="uni-button" type="primary"
						style="margin-right: 75px;">添加</button>
					<button v-if="hasadmin" @click="managerMultiTag('del')" class="uni-button" type="warn">删除</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		fee_statue_text,
		enumConverter,
		filterToWhere
	} from '../../../js_sdk/validator/uni-id-users.js';

	const db = uniCloud.database()
	const dbCmd = db.command
	// 表查询配置
	const dbOrderBy = 'register_date desc' // 排序字段
	const dbSearchFields = ['username', 'role.role_name', 'mobile', 'email'] // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				collection:[
					     db.collection('uni-id-users')
						  .where(this.where)
						  .field('username,student_name,mobile,status,test_times,type_cert_id,type_drive_id,login_times,use_times,type_subject_id,fee_status,email,dcloud_appid,tags,register_date,mechanism_id,role')
						  .getTemp()
						 ,
					     db.collection('uni-id-roles').getTemp()
				],
				searchParams: {
					username: '',
					student_name: '',
					mobile: ''
				},
				certList: {},
				driveList: {},
				subjectList: {},

				mechanism_id: '',
				query: '',
				where: {

				},
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				pageSizeIndex: 0,
				pageSizeOption: [20, 50, 100, 500],
				tags: {},
				managerTags: [],
				queryTagid: '',
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"status_localdata": [{
								"text": "未缴费",
								"value": 0
							}, {
								"text": "已缴费",
								"value": 1
							}, {
								"text": "已毕业",
								"value": 2
							},
							{
								"text": "已过期",
								"value": 3
							}, {
								"text": "禁用",
								"value": 4
							}
						]
					},
					...fee_statue_text,
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "uni-id-users.xls",
					"type": "xls",
					"fields": {
						"用户名": "username",
						"手机号码": "mobile",
						"用户状态": "status",
						"邮箱": "email",
						"角色": "role",
						"register_date": "register_date"
					}
				},
				exportExcelData: [],
				noAppidWhatShouldIDoLink: 'https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=makeup-dcloud-appid',
				roleMap: {
					'jigou': 'jiaoshi',
					'jiaoshi': "xueshen"
				},
				queryRole: {},
				needRole: '',
				mechanismMap: {}
			}
		},
		onLoad(e) {
			this._filter = {}
			this.mechanismMap = new Map()
			this.initMapInfo()
			const tagid = e.tagid
			if (tagid) {
				this.queryTagid = tagid
				const options = {
					filterType: "select",
					filter: [tagid]
				}
				this.filterChange(options, "tags")
			}

			if (this.uniIDHasRole('admin') || this.uniIDHasRole('XZID')) {
				this.hasadmin = true
				this.queryRole['role.role_id'] = db.command.eq('xueshen')
				console.log('has admin')
				this.where = this.queryRole
			} else {
				const mechanism = uni.getStorageSync('mechanism')
				const u = uniCloud.getCurrentUserInfo()
				console.log(mechanism)
				this.queryRole['role.role_id'] = db.command.eq('xueshen')
				this.queryRole['mechanism_id'] = db.command.eq(mechanism)
				this.mechanism_id = mechanism
				this.needRole = 'xueshen'
				this.where = this.queryRole
			}
			this.getMeName()
		},
		onReady() {
			this.loadTags()
			if (!this.queryTagid) {
				this.$refs.udb.loadData()
			}
		},
		watch: {
			pageSizeIndex: {
				immediate: true,
				handler(val, old) {
					this.options.pageSize = this.pageSizeOption[val]
					this.options.pageCurrent = 1
					this.$nextTick(() => {
						this.loadData()
					})
				}
			}
		},
		computed: {
			getInfoWhere() {
				return this.where
			},
			tagsData() {
				const dynamic_data = []
				for (const key in this.tags) {
					const tag = {
						value: key,
						text: this.tags[key]
					}
					if (key === this.queryTagid) {
						tag.checked = true
					}
					dynamic_data.push(tag)
				}
				return dynamic_data
			}
		},
		onShow() {
			console.log(this.options.text)
			// if (this.$refs.udb) {
			// 	this.$refs.udb.refresh()
			// }
		},
		methods: {
			async initMapInfo() {
				const self = this
				const t1 = await db.collection('type-cert').get()
				const t2 = await db.collection('type-drive').get()
				const t3 = await db.collection('type-subject').get()

				t1.result.data.forEach(e => {
					self.certList[e.sid] = e.name
				})

				t2.result.data.forEach(e => {
					self.driveList[e.sid] = e.name
				})

				t3.result.data.forEach(e => {
					self.subjectList[e.sid] = e.name
				})

			},
			getNameValue(key) {
				return this.mechanismMap.get(key)
			},
			async getMeName() {
				const data = await db.collection('mechanism').field("_id,name").limit(500).get()
				for (let d of data.result.data) {
					this.mechanismMap.set(d._id, d.name)
				}
			},
			toEdit(item) {
				uni.navigateTo({
					url: './edit?id=' + item._id + `&mechanism=${item.mechanism_id}`
				})
			},
			toAdd() {
				if (!this.hasadmin) {
					uni.navigateTo({
						url: './add?mechanism=' + this.mechanism_id
					})
				} else {
					uni.navigateTo({
						url: './add'
					})
				}
			},
			onqueryload(data) {
				for (var i = 0; i < data.length; i++) {
					let item = data[i]
					const roleArr = item.role.map(item => item.role_name)
					item.role = roleArr.join('、')
					const tagsArr = item.tags && item.tags.map(item => this.tags[item])
					item.tags = tagsArr
					if (Array.isArray(item.dcloud_appid)) {
						item.dcloud_appid = item.dcloud_appid.join('、')
					}
					item.register_date = this.$formatDate(item.register_date)
				}
				this.exportExcelData = data
			},
			changeSize(e) {
				this.pageSizeIndex = e.detail.value
			},
			openTagsPopup() {
				this.$refs.tagsPopup.open()
			},
			closeTagsPopup() {
				this.$refs.tagsPopup.close()
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {

				let newWhere = {}
				newWhere['role.role_id'] = db.command.eq('xueshen')
				if (!this.uniIDHasRole('admin') && !this.uniIDHasRole('XZID')) {
					newWhere['mechanism_id'] = db.command.eq(this.mechanism_id)
				}

				for (const k of Object.keys(this.searchParams)) {
					const s_params = this.searchParams[k]
					if (this.searchParams[k] !== '') {
						newWhere[k] = new RegExp(s_params, 'i')
					}
				}

				this.where = newWhere
				// 下一帧拿到查询条件
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadTags()
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)

				newWhere['role.role_id'] = db.command.eq('xueshen')


				if (!this.uniIDHasRole('admin')) {
					newWhere['mechanism_id'] = db.command.eq(this.mechanism_id)
				}
				console.log(newWhere)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			loadTags() {
				db.collection('uni-id-tag').limit(500).get().then(res => {
					res.result.data.map(item => {
						this.tags[item.tagid] = item.name
					})
				}).catch(err => {
					uni.showModal({
						title: '提示',
						content: err.message,
						showCancel: false
					})
				})
			},
			managerMultiTag(type) {
				const ids = this.selectedItems()
				const options = {
					type,
					ids,
					value: this.managerTags
				}
				this.$request('managerMultiTag', options, {
					functionName: 'uni-id-cf'
				}).then(res => {
					uni.showToast({
						title: '修改标签成功',
						duration: 2000
					})
					this.$refs.table.clearSelection()
					this.managerTags = []
					this.loadData()
					this.closeTagsPopup()
				}).catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(err => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style lang="scss">
	.tags-manager {

		&--x {
			width: 400px;
			padding: 40px 30px;
			border-radius: 5px;
			background-color: #fff;
		}

		&--header {
			font-size: 22px;
			color: #333;
			text-align: center;
		}
	}

	.mb {
		margin-bottom: 80px;
	}

	.ml {
		margin-left: 30px;
	}
</style>
